<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/10/18
 * Time: 14:53
 */

namespace Hrm\Controllers;

use Admin\Frontend\Controllers\ControllerBase;
use Admin\Models\hrm\XhhrmApprove;
use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\hrm\XhhrmExperience;
use Admin\Models\hrm\XhhrmResource;
use Admin\Models\hrm\XhhrmStaff;
use Admin\Models\hrm\XhhrmStaffContact;
use Admin\Models\hrm\XhhrmStaffDismiss;
use Admin\Models\hrm\XhhrmStaffRegular;
use Admin\Models\hrm\XhhrmStaffTransfer;
use Admin\Models\sys\XhsysConfig;
use Helpers\Assets;
use Helpers\Device;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\XhException;
use Modules\Lm;
use Modules\Power;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Model\Relation;
use Services\HundredMail;

class MineController extends ControllerBase
{
    public function beforeExecuteRoute(Dispatcher $dispatcher)
    {
//        if (in_array(strtolower($dispatcher->getActionName()), [
//            strtolower('index'),
//            strtolower('getStaff'),
//        ])) {
//            return true;
//        }
        //检查是否已登陆，否则跳转到登陆页面
        if (!User::isLogin()) {
            Main::goLoginPage();
            return false;
        }
        return true;
    }

    public static $regularEnum = [
        'iState' => [
            1 => '<div class="grid-cell-text-bg-gray">等待补充信息</div>',
            2 => '<div class="grid-cell-text-bg-blue">部门审批</div>',
            3 => '<div class="grid-cell-text-bg-yellow">人力资源审批</div>',
            4 => '<div class="grid-cell-text-bg-green">总经理审批</div>',
            5 => '<div class="grid-cell-text-bg-green">审批通过</div>',
            6 => '<div class="grid-cell-text-bg-red">审批不通过</div>'
        ]
    ];

    public static $enums = [
        'iUserSex' => ['1' => '男', 2 => '女'],
    ];

    public static $transferEnum = [
        'iState' => [
            1 => '<div class="grid-cell-text-bg-gray">个人意见</div>',
            2 => '<div class="grid-cell-text-bg-blue">调出部门意见</div>',
            3 => '<div class="grid-cell-text-bg-blue">调入部门意见</div>',
            4 => '<div class="grid-cell-text-bg-yellow">人力资源审批</div>',
            5 => '<div class="grid-cell-text-bg-green">总经理审批</div>',
            6 => '<div class="grid-cell-text-bg-green">审批通过</div>',
            7 => '<div class="grid-cell-text-bg-red">审批不通过</div>'
        ],
        'iType' => [
            1 => '调动',
            2 => '借调'
        ]
    ];

    public static $dismissEnum = [
        'iState' => [
            1 => '<div class="grid-cell-text-bg-gray">部门审批</div>',
            2 => '<div class="grid-cell-text-bg-gray">人力资源审批</div>',
            3 => '<div class="grid-cell-text-bg-gray">总经理审批</div>',
            4 => '<div class="grid-cell-text-bg-green">审批通过</div>',
            5 => '<div class="grid-cell-text-bg-red">审批不通过</div>'
        ],
        'iUserSex' => ['1' => '男', 2 => '女'],
    ];

    public static $checkType = [
        'regular' => [
            'dep' => '部门审核',
            'resource' => '人力资源审核',
            'manager' => '总经理审核'
        ],
        'transfer' => [
            'mine' => '个人意见',
            'outDep' => '调出部门意见',
            'inDep' => '调入部门意见',
            'resource' => '人力资源意见',
            'manager' => '总经理意见'
        ],
        'dismiss' => [
            'dep' => '部门审核',
            'resource' => '人力资源审核',
            'manager' => '总经理审核'
        ],
    ];

    /**
     * 获取当前登陆的职工id
     *
     * @return int
     * @throws \Exception
     *
     * create by dale  20181226
     */
    private function getLoginStaffId()
    {
        if (!User::isAdmin()) {
            $userId = Main::getLoginUserInfo('userId');
            $staff = XhhrmStaff::findFirst([
                'columns'    => 'iStaffId',
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind'       => ['iUserId' => $userId]
            ]);
            if (!$staff) {
                throw new \Exception('没有职工信息');
            }
            $staffId = $staff->iStaffId;
        } else {
            $config     = Main::getConfigByName('hrm');
            $adminPhone = Tool::getValue($config, 'adminStaffPhone');
            if (!$adminPhone) {
                throw new \Exception('没有hrm:adminStaffPhone配置项');
            }
            $staff = XhhrmStaff::findFirst([
                'columns'    => 'iStaffId',
                'conditions' => 'bDelete = 0 and sSelfPhone = :sSelfPhone:',
                'bind'       => ['sSelfPhone' => $adminPhone]
            ]);
            if (!$staff) {
                throw new \Exception('没有职工信息');
            }
            $staffId = $staff->iStaffId;
        }
        return $staffId;
    }

    /**
     * 个人中心
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181018
     */
    public function indexAction()
    {
        try {
            $this->view->pick('mine/index');
            Assets::importJs('js/mine/index.js');
            $staffId = $this->getLoginStaffId();
            $checkRegular = XhhrmStaffRegular::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId: and iState != 6',
                'bind'       => ['iStaffId' => $staffId]
            ]);
            $checkTransfer = XhhrmStaffTransfer::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId: and iState != 7 and iState != 6  ',
                'bind'       => ['iStaffId' => $staffId]
            ]);
            $checkDismiss = XhhrmStaffDismiss::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId: and iState != 4 and iState != 5  ',
                'bind'       => ['iStaffId' => $staffId]
            ]);
            $staff = XhhrmStaff::getStaffInfo($staffId);
//            if ($staff['tBirthday']) {
//                $staff['iAge'] = XhhrmStaff::calculateAge($staff['tBirthday']);
//            }
//            if ($staff['tHireDate']) {
//               $staff['sCompanyYear'] = $this->getAge($staff['tHireDate']);
//            }
            return $this->view->setVars([
                'staffId' => $staffId,
                'checkRegular' => $checkRegular ? true : false,
                'checkTransfer' => $checkTransfer ? true : false,
                'checkDismiss' => $checkDismiss ? true : false,
                'staffInfo'    => $staff
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 审核列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181023
     */
    public function checkTabAction()
    {
        try {
            $this->view->pick('mine/checkTab');
            Assets::importJs('js/mine/checkTab.js');
            return  $this->view->setVars([

            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }


    /**
     * 申请转正
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181018
     */
    public function completeRegularAction()
    {
        try {
            $id = $this->request->getQuery('id', 'int');
            if (!$id) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('mine/completeRegular');
            Assets::importJs('js/mine/completeRegular.js');
            $regularColumns =  array_keys(get_object_vars(new XhhrmStaffRegular()));
            $regularColumns = array_map(function ($val) {
                return 'r.' . $val;
            }, $regularColumns);
            $builder = $this->modelsManager->createBuilder()
                ->from(['r' => 'Admin\Models\hrm\XhhrmStaffRegular'])
                ->columns(array_merge($regularColumns, ['s.tHireDate','s.sDepIds','s.sPostName','s.sStaffName']))
                ->leftJoin('Admin\Models\hrm\XhhrmStaff', 'r.iStaffId = s.iStaffId', 's')
                ->where('s.bDelete = 0 and r.iSPId = :iSPId:', ['iSPId' => $id])
                ->limit(1);
            $info = $builder->getQuery()->execute()->toArray();
            if ($info) {
                $info = $info[0];
                if ($info['sDepIds']) {
                    $depArr = array_values(array_filter(explode(',', $info['sDepIds'])));
                    if ($depArr) {
                        $info['sDepName'] = Tool::getValue(XhhrmDepart::getDepEnum(), end($depArr), '');
                    }
                }
                $this->view->setVar('info', $info);
            }
            return $this->view->setVars([
                'staffId' => $info['iStaffId']
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 发起转正
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181019
     */
    public function addRegularAction()
    {
        try {
            $staffId = $this->request->getPost('staffId', 'int');
            $desc    = $this->request->getPost('desc', 'string');
            if (!$staffId) {
                return $this->sendErrorResponse(500, '缺少职工id');
            }
            $check = XhhrmStaffRegular::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId: and iState != 6',
                'bind'       => ['iStaffId' => $staffId],
            ]);
            if ($check) {
                return $this->sendErrorResponse(400, '试用转正已经存在请勿重复创建');
            }
            $obj = new XhhrmStaffRegular();
            $obj->iStaffId = $staffId;
            $obj->mDesc =$desc;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '申请保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 转正审核
     *
     * @return string
     *
     * create by dale  20181019
     */
    public function regularListAction()
    {
        try {
            Assets::easyUI();
            Assets::importJs('js/mine/regularList.js');
            $this->view->setTemplateBefore('listForm');
            $this->view->pick('mine/regularList');
            Template::exists('Mine_Regular', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
            $listButtonArr = $formButtonArr = $listSearchArr = array();
            $state = array_map(function ($val) {
                return strip_tags($val);
            }, self::$regularEnum['iState']);
            $listSearchArr[] = ['type'=>'select', 'id'=>'select_state', 'data'=>['' => '全部'] + $state,
                'default' => '' ];
            $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
                'icon' => 'fa-search', 'style' => 'margin-left:10px');

            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_check', 'text' => '审批', 'icon' => 'fa-check');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_seeCheck', 'text' => '查看历史',
                'icon' => 'fa-eye');
            return $this->view->setVars([
                'List' => Template::createList('list', 'Mine_Regular', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                ]),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }



    /**
     * 获取入职申请数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181019
     */
    public function getRegularAction()
    {
        try {
            $staffId = $this->request->getPost('staffId', 'int');
            $state   = $this->request->getPost('state', 'string');
            $key     = $this->request->getPost('key', 'string');
            $regularColumns =  array_keys(get_object_vars(new XhhrmStaffRegular()));
            $regularColumns = array_map(function ($val) {
                return 'r.' . $val;
            }, $regularColumns);
            $depEnum = XhhrmDepart::getDepEnum();
            $builder = $this->modelsManager->createBuilder()
                ->from(['r' => 'Admin\Models\hrm\XhhrmStaffRegular'])
                ->columns(array_merge($regularColumns, ['s.tHireDate','s.sDepIds','s.sPostName','s.sStaffName']))
                ->leftJoin('Admin\Models\hrm\XhhrmStaff', 'r.iStaffId = s.iStaffId', 's')
                ->where('r.bDelete = 0');
            if ($staffId) {
                $builder->andWhere('r.iStaffId = :iStaffId:', ['iStaffId' => $staffId]);
            }
            if ($state) {
                $builder->andWhere('r.iState = :iState:', ['iState' => $state]);
            }
            if ($key) {
                $builder->andWhere('s.sStaffName like :key:', ['key' => '%'.$key.'%']);
            }
            $data = Main::runBuilderPage($builder, self::$regularEnum);
            foreach ($data['rows'] as $index => &$row) {
                if ($row['sDepIds']) {
                    $depArr = array_values(array_filter(explode(',', $row['sDepIds'])));
                    if ($depArr) {
                        $row['sDepName'] = Tool::getValue($depEnum, end($depArr), '');
                    }
                }
                $row['mDesc'] = "<div  title='{$row['mDesc']}'
                            style='text-overflow: ellipsis;overflow: hidden;'>{$row['mDesc']}</div>";
            }
            Main::runUserNameById(
                $data['rows'],
                ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'],
                true
            );
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 补充转正信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181020
     */
    public function saveRegularAction()
    {
        try {
            $iSPId = $this->request->getPost('iSPId', 'int');
            $state = $this->request->getPost('state', 'int');
            if (!$iSPId || !$state) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmStaffRegular::findFirst($iSPId);
            if (!$obj) {
                return $this->sendErrorResponse(400, '未找到记录');
            }
            $this->db->begin();
            $postData = $this->request->getPost();
            $postData = array_filter($postData);
            $obj->assign($postData);
            if ($obj->sContentDate && $obj->sProbationDate &&
                $obj->sProbationSalary && $obj->tRegularDate &&
                $obj->sRegularSalary && $obj->iState == 1) {
                $obj->iState = $state;
            }
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 审批
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View
     *
     * create by dale  20181020
     */
    public function regularCheckAction()
    {
        try {
            $id = $this->request->getQuery('id', 'string');
            if (!$id) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('mine/regularCheck');
            Assets::importJs('js/mine/regularCheck.js');
            $info = XhhrmStaffRegular::findFirst($id);
            if (!$info) {
                return $this->sendViewError('未找到对应记录');
            }
            if ($info->iState == 1) {
                return $this->sendViewError('请先补全信息');
            }
            if (!User::isAdmin()) {
                $staff = XhhrmStaff::findFirst([
                    'columns'    => 'iStaffId,sDepIds',
                    'conditions' => 'bDelete = 0 and iStaffId = :iStaffId:',
                    'bind'       => ['iStaffId' => $info->iStaffId],
                ]);
                if (!$staff) {
                    return $this->sendViewError('未找到职工信息');
                }
                $depId = array_values(array_filter(explode(',', $staff->sDepIds)));
                $depId = end($depId);
                if (!$depId) {
                    return $this->sendViewError('未找到职工的部门信息');
                }
                $dep = XhhrmDepart::findFirst([
                    'conditions' => 'bDelete = 0 and iDepId = :iDepId:',
                    'bind'       => ['iDepId' => $depId]
                ]);
                if (!$dep || !$dep->sTag) {
                    return $this->sendViewError('未找到部门标识或者部门不存在');
                }
                if ($info->iState == 2 && !$this->hasCheckPower('dep', $dep->sTag)) {
                    return $this->sendViewError('没有权限');
                }
                if ($info->iState == 3 && !$this->hasCheckPower('resource', 'XHRLB')) {
                    return $this->sendViewError('没有权限');
                }
                if ($info->iState == 4 && !$this->hasCheckPower('manager')) {
                    return $this->sendViewError('没有权限');
                }
            }
            return $this->view->setVars([
                'info' => $info->toArray()
            ]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 改变试用期状态
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181022
     */
    public function changeRegularStatusAction()
    {
        try {
            $id   = $this->request->getPost('id', 'int');
            $pass = $this->request->getPost('pass', 'int');//1 通过 2 不通过
            $desc = $this->request->getPost('desc', 'string');
            if (!$id || !$pass || !$desc) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmStaffRegular::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(400, '未找到对应的记录');
            }
            if ($obj->iState == 1) {
                return $this->sendErrorResponse(500, '请先补充信息');
            }
            if ($obj->iState == 5) {
                return $this->sendErrorResponse(500, '已经审批通过');
            }
            if ($obj->iState == 6) {
                return $this->sendErrorResponse(500, '已经审批不通过');
            }
            $staff = XhhrmStaff::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId:',
                'bind'       => ['iStaffId' => $obj->iStaffId],
            ]);
            if (!$staff) {
                return $this->sendErrorResponse(400, '未找到职工信息');
            }
            if ($staff->iOfferStatus && $staff->iOfferStatus == 2) {
                return $this->sendErrorResponse(500, '该职工已经转正');
            }
            if (!User::isAdmin()) { //判断权限
                $depId = array_values(array_filter(explode(',', $staff->sDepIds)));
                $depId = end($depId);
                if (!$depId) {
                    return $this->sendErrorResponse(400, '未找到职工的部门信息');
                }
                $dep = XhhrmDepart::findFirst([
                    'conditions' => 'bDelete = 0 and iDepId = :iDepId:',
                    'bind'       => ['iDepId' => $depId]
                ]);
                if (!$dep || !$dep->sTag) {
                    return $this->sendErrorResponse(400, '未找到部门标识或者部门不存在');
                }
                if ($obj->iState == 2 && !$this->hasCheckPower('dep', $dep->sTag)) {
                    return $this->sendErrorResponse(403, '没有权限');
                }
                if ($obj->iState == 3 && !$this->hasCheckPower('resource', 'XHRLB')) {
                    return $this->sendErrorResponse(403, '没有权限');
                }
                if ($obj->iState == 4 && !$this->hasCheckPower('manager')) {
                    return $this->sendErrorResponse(403, '没有权限');
                }
            }
            switch ($obj->iState) {
                case 2:
                    $type = 'dep';
                    break;
                case 3:
                    $type = 'resource';
                    break;
                case 4:
                    $type = 'manager';
                    break;
                default:
                    $type = '';
            }
            if (!$type) {
                return $this->sendErrorResponse(400, '未知状态');
            }
            $this->db->begin();
            if ($pass == 1) {
                $obj->iState = $obj->iState + 1 ;
            } elseif ($pass == 2) {
                $obj->iState = 6 ;
            } else {
                return $this->sendErrorResponse(500, '未知操作类型');
            }
            if ($obj->mHistory == null) {
                $history = [
                    [
                        'date'       => date('Y-m-d H:i:s'),
                        'operatorId' => Main::getLoginUserInfo('userId'),
                        'desc'       => $desc,
                        'pass'       => $pass == 1 ? '通过': '不通过',
                        'type'       => $type
                    ]
                ];
            } else {
                $history = json_decode($obj->mHistory, true);
                $history[] = [
                    'date'       => date('Y-m-d H:i:s'),
                    'operatorId' => Main::getLoginUserInfo('userId'),
                    'desc'       => $desc,
                    'pass'       => $pass == 1 ? '通过': '不通过',
                    'type'       => $type
                ];
            }
            $obj->mHistory = json_encode($history, JSON_UNESCAPED_UNICODE);
            if (!$obj->save()) {
                throw new XhException('保存失败');
            }
            if ($obj->iState == 5) {
                $staff->iOfferStatus = 2;
                if ($staff->mHistory == null) {
                    $staff->mHistory = json_encode([
                        [
                            'time' =>  date('Y-m-d'),
                            'type' => 'iOfferStatus',
                            'status' => 2,
                            'operator' => Main::getLoginUserInfo('userId'),
                            'operateTime' => date("Y-m-d H:i:s", time())
                        ]
                    ]);
                } else {
                    $arr = json_decode($staff->mHistory, true);
                    $arr[] = [
                        'time' =>  date('Y-m-d'),
                        'type' => 'iOfferStatus',
                        'status' => 2,
                        'operator' => Main::getLoginUserInfo('userId'),
                        'operateTime' => date("Y-m-d H:i:s", time())
                    ];
                    $staff->mHistory = json_encode($arr);
                }
                $staff->sContentDate = $obj->sContentDate;
                $staff->sProbationDate = $obj->sProbationDate;
                $staff->sProbationSalary = $obj->sProbationSalary;
                $staff->tRegularDate = $obj->tRegularDate;
                $staff->sRegularSalary = $obj->sRegularSalary;
                if (!$staff->save()) {
                    throw new XhException('转正申请失败');
                }
            }
            $approve = new XhhrmApprove();
            $approve->sType = 'regular';
            $approve->sVerifier = $type;
            $approve->mDesc = $desc;
            $approve->iUserId = Main::getLoginUserInfo('userId');
            $approve->iTargetId = $obj->iSPId;
            $approve->sDate     = date('Y-m-d');
            $approve->bPass     = $pass;
            if (!$approve->save()) {
                throw new XhException('保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 判断审批权限
     *
     * @param $type
     * @param string $depTag
     * @param string $powerTag
     *
     * @return bool
     * @throws XhException
     *
     * create by dale  20181020
     */
    public function hasCheckPower($type, $depTag = '', $powerTag = '')
    {
        if (in_array($type, ['dep', 'resource'])) {
            if (!$depTag) {
                throw new XhException('部门标识必传');
            }
            $dep = XhhrmDepart::findFirst([
                'column'     => 'iDepId',
                'conditions' => 'bDelete = 0 and sTag = :sTag:',
                'bind'       => ['sTag' => $depTag]
            ]);
            if (!$dep) {
                throw new XhException('未找到该标识的部门');
            }
            $depId = $dep->iDepId;
//            $sql = "select iUserId from XHHrm_Staff  WHERE find_in_set('".$depId."',sChargeDeps) and bDelete = 0";
//            $chargeId = $this->db->fetchOne($sql);
//            if (!$chargeId) {
//                return false;
//            }
//            $chargeId = Tool::getValue($chargeId, 'iUserId');
//            $userId = Main::getLoginUserInfo('userId');
//            if ($chargeId == $userId) {
//                return true;
//            }
            $userId = Main::getLoginUserInfo('userId');
            $sql = "select iUserId from XHHrm_Staff  WHERE find_in_set('".$depId."',sDepIds) 
                    and bDelete = 0 and iUserId = {$userId} ";
            $checkInDep = $this->db->fetchOne($sql);
            if (!$checkInDep) {  //判断是否在部门
                return false;
            }
            if ($powerTag) {
                if (!Power::exist($powerTag)) {
                    return false;
                }
            }
            return true;
        } elseif (in_array($type, ['manager'])) {
            $hrmConfig = Main::getConfigByName('hrm');
            if (!$hrmConfig) {
                throw new XhException('hrm配置项不存在');
            }
            $manager = Tool::getValue($hrmConfig, 'manager');
            if (!$manager) {
                throw new XhException('hrm->manager配置项不存在');
            }
            $managerArr = explode(',', $manager);
            $staff = XhhrmStaff::findFirst([
                'columns'    => 'sSelfPhone',
                'conditions' => 'bDelete = 0 and iUserId = :iUserId:',
                'bind'       => ['iUserId' => Main::getLoginUserInfo('userId')]
            ]);
            if (!$staff) {
                return false;
            }
            if (!$staff->sSelfPhone) {
                return false;
            }
            if (in_array(Main::getLoginUserInfo('logonName'), $managerArr) || in_array($staff->sSelfPhone, $managerArr)) {
                return true;
            }
            return false;
        } else {
            throw new XhException('未知type类型');
        }
    }

    /**
     * 调岗列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181022
     */
    public function transferListAction()
    {
        try {
            Assets::easyUI();
            Assets::importJs('js/mine/transferList.js');
            $this->view->setTemplateBefore('listForm');
            $this->view->pick('mine/transferList');
            Template::exists('Mine_TransFer', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
            $listButtonArr = $formButtonArr = $listSearchArr = array();
            $state = array_map(function ($val) {
                return strip_tags($val);
            }, self::$transferEnum['iState']);
            $listSearchArr[] = ['type'=>'select', 'id'=>'select_state', 'data'=>['' => '全部'] + $state,
                'default' => '' ,'style' => 'width: 102px;'];
            $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
                'icon' => 'fa-search', 'style' => 'margin-left:10px');

            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_check', 'text' => '审批', 'icon' => 'fa-check');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_seeCheck', 'text' => '查看历史',
                'icon' => 'fa-eye');
            return $this->view->setVars([
                'List' => Template::createList('list', 'Mine_TransFer', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                ]),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }




    /**
     * 审核信息
     *
     * @param string $sTag
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View|string
     *
     * create by dale  20181031
     */
    public function checkListAction($sTag = '')
    {
        try {
            if (!$sTag) {
                return $this->sendErrorResponse(500, '审核失败');
            }
            $this->view->pick('mine/checkList');
//            Assets::importJs('js/mine/checkList.js');
            $id = $this->request->getQuery('id', 'string');
            if (!$id) {
                return $this->sendViewError('没有id');
            }
            $approveArr = XhhrmApprove::find([
                'conditions' => 'bDelete = 0 and sType = :sType: and iTargetId = :iTargetId:',
                'bind'       => ['iTargetId' => $id, 'sType' => $sTag]
            ])->toArray();
            if (!$approveArr) {
                return $this->sendViewError('暂无数据');
            }
            Main::runUserName($approveArr, ['iUserId' => 'iUserId'], false);
//            var_dump($approveArr);die;
            return $this->view->setVars([
                'infoArr' => $approveArr,
                'checkType' => self::$checkType
            ]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 获取转换
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181023
     */
    public function getTransferAction()
    {
        try {
            $staffId = $this->request->getPost('staffId', 'int');
            $state   = $this->request->getPost('state', 'string');
            $key     = $this->request->getPost('key', 'string');
            $regularColumns =  array_keys(get_object_vars(new XhhrmStaffTransfer()));
            $regularColumns = array_map(function ($val) {
                return 't.' . $val;
            }, $regularColumns);
            $depEnum = XhhrmDepart::getDepEnum();
            $builder = $this->modelsManager->createBuilder()
                ->from(['t' => 'Admin\Models\hrm\XhhrmStaffTransfer'])
                ->columns(array_merge($regularColumns, ['s.sStaffName']))
                ->leftJoin('Admin\Models\hrm\XhhrmStaff', 't.iStaffId = s.iStaffId', 's')
                ->where('t.bDelete = 0');
            if ($staffId) {
                $builder->andWhere('t.iStaffId = :iStaffId:', ['iStaffId' => $staffId]);
            }
            if ($state) {
                $builder->andWhere('t.iState = :iState:', ['iState' => $state]);
            }
            if ($key) {
                $builder->andWhere('s.sStaffName like :key:', ['key' => '%'.$key.'%']);
            }
            $data = Main::runBuilderPage($builder, self::$transferEnum);
            foreach ($data['rows'] as $index => &$row) {
                if ($row['sDepIds']) {
                    $depArr = array_values(array_filter(explode(',', $row['sDepIds'])));
                    if ($depArr) {
                        $row['sDepName'] = Tool::getValue($depEnum, end($depArr), '');
                    }
                }
                $row['mDesc'] = "<div  title='{$row['mDesc']}'
                            style='text-overflow: ellipsis;overflow: hidden;'>{$row['mDesc']}</div>";
                if ($row['sInDepId']) {
                    $row['sInDepId'] = XhhrmDepart::getDepName($row['sInDepId']);
                }
                if ($row['sOutDepId']) {
                    $row['sOutDepId'] = XhhrmDepart::getDepName($row['sOutDepId']);
                }
            }
            Main::runUserNameById(
                $data['rows'],
                ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'],
                true
            );
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 员工调动意见表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181025
     */
    public function transferFormAction()
    {
        try {
            $staffId = $this->request->getQuery('staffId', 'int');
            if (!$staffId) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('mine/transferForm');
            Assets::select2();
            Assets::importJs('js/mine/transferForm.js');
            $staffInfo = XhhrmStaff::findFirst($staffId);
            if (!$staffInfo) {
                return $this->sendViewError('未找到职工信息');
            }
            $staffInfo = $staffInfo->toArray();
            if ($staffInfo) {
                $staffInfo['age'] = $this->getAge($staffInfo['tBirthday']);
                $staffInfo['iUserSex'] =  Tool::getValue(self::$enums['iUserSex'], $staffInfo['iUserSex'], '');
                $staffInfo['sDepName'] = XhhrmDepart::getDepName($staffInfo['sDepIds']);
            }

            return $this->view->setVars([
                'staffInfo' => $staffInfo,
                'depArr'    => XhhrmDepart::getDepEnum(),
                'staffId'   => $staffId,
                'transType' => self::$transferEnum['iType']
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 员工调动
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181024
     */
    public function addTransferAction()
    {
        try {
            $staffId   = $this->request->getPost('staffId', 'int');
            $postData  = $this->request->getPost();
            if (!$staffId) {
                return $this->sendErrorResponse(500, '缺少职工id');
            }
            $check = XhhrmStaffTransfer::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId: and iState != 7 and iState != 6  ',
                'bind'       => ['iStaffId' => $staffId],
            ]);
            if ($check) {
                return $this->sendErrorResponse(400, '员工调动已经存在请勿重复创建');
            }
            $obj = new XhhrmStaffTransfer();
            $obj->assign($postData);
            $staff = XhhrmStaff::findFirst($staffId);
            if (!$staff) {
                return $this->sendErrorResponse(500, '未找到该职工');
            }
            $depId = Tool::getValue($postData, 'sInDepId');
            if ($depId) {
                $depArr = XhhrmDepart::getDepIdArr($depId);
                $sDepIds = ','.implode(',', $depArr).',';
                $obj->sInDepId = $sDepIds;
            }
            $obj->sOutDepId = $staff->sDepIds;
            $obj->sOutPost  = $staff->sPostName;
            $obj->sOutSalary = $staff->sRegularSalary;
            $obj->iStaffId = $staffId;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '申请保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 调岗审核
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View|string
     *
     * create by dale  20181029
     */
    public function transferCheckAction()
    {
        try {
            $id = $this->request->getQuery('id', 'string');
            if (!$id) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('mine/transferCheck');
            Assets::importJs('js/mine/transferCheck.js');
            $info = XhhrmStaffTransfer::findFirst($id);
            if (!$info) {
                return $this->sendViewError('未找到对应记录');
            }
            if (!User::isAdmin()) {
                $staff = XhhrmStaff::findFirst([
                    'columns'    => 'iStaffId,sDepIds,iUserId',
                    'conditions' => 'bDelete = 0 and iStaffId = :iStaffId:',
                    'bind'       => ['iStaffId' => $info->iStaffId],
                ]);
                if (!$staff) {
                    return $this->sendViewError('未找到职工信息');
                }
                if ($info->iState == 1 && Main::getLoginUserInfo('userId') != $staff->iUserId) {
                    return $this->sendErrorResponse('没有权限');
                }
                $outDepId = end(array_values(array_filter(explode(',', $info->sOutDepId))));
                $inDepId = end(array_values(array_filter(explode(',', $info->sInDepId))));
                if (!$outDepId) {
                    return $this->sendViewError('未找到职工的部门信息');
                }
                $outDep = XhhrmDepart::findFirst([
                    'columns'    => 'sTag',
                    'conditions' => 'bDelete = 0 and iDepId = :iDepId:',
                    'bind'       => ['iDepId' => $outDepId]
                ]);
                $inDep = XhhrmDepart::findFirst([
                    'columns'    => 'sTag',
                    'conditions' => 'bDelete = 0 and iDepId = :iDepId:',
                    'bind'       => ['iDepId' => $inDepId]
                ]);
                if (!$outDep || !$outDep->sTag || !$inDep || !$inDep->sTag) {
                    return $this->sendViewError('未找到部门标识或者部门不存在');
                }
                if ($info->iState == 2 && !$this->hasCheckPower('dep', $outDep->sTag)) {
                    return $this->sendErrorResponse('没有权限');
                }
                if ($info->iState == 3 && !$this->hasCheckPower('dep', $inDep->sTag)) {
                    return $this->sendErrorResponse('没有权限');
                }
                if ($info->iState == 4 && !$this->hasCheckPower('resource', 'XHRLB')) {
                    return $this->sendErrorResponse('没有权限');
                }
                if ($info->iState == 5 && !$this->hasCheckPower('manager')) {
                    return $this->sendErrorResponse('没有权限');
                }
            }
            return $this->view->setVars([
                'info' => $info->toArray()
            ]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 改变调岗审批状态
     *
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181029
     */
    public function changeTransferStatusAction()
    {
        try {
            $id   = $this->request->getPost('id', 'int');
            $pass = $this->request->getPost('pass', 'int');//1 通过 2 不通过
            $desc = $this->request->getPost('desc', 'string');
            if (!$id || !$pass || !$desc) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmStaffTransfer::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(400, '未找到对应的记录');
            }
            if ($obj->iState == 6) {
                return $this->sendErrorResponse(500, '已经审批通过');
            }
            if ($obj->iState == 7) {
                return $this->sendErrorResponse(500, '已经审批不通过');
            }
            $staff = XhhrmStaff::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId:',
                'bind'       => ['iStaffId' => $obj->iStaffId],
            ]);
            if (!$staff) {
                return $this->sendErrorResponse(400, '未找到职工信息');
            }
//            if ($staff->iOfferStatus && $staff->iOfferStatus == 2) {
//                return $this->sendErrorResponse(500, '该职工已经转正');
//            }
            if (!User::isAdmin()) { //判断权限
                $outDepId = end(array_values(array_filter(explode(',', $obj->sOutDepId))));
                $inDepId = end(array_values(array_filter(explode(',', $obj->sInDepId))));
                if (!$outDepId) {
                    return $this->sendViewError('未找到职工的部门信息');
                }
                $outDep = XhhrmDepart::findFirst([
                    'columns'    => 'sTag',
                    'conditions' => 'bDelete = 0 and iDepId = :iDepId:',
                    'bind'       => ['iDepId' => $outDepId]
                ]);
                $inDep = XhhrmDepart::findFirst([
                    'columns'    => 'sTag',
                    'conditions' => 'bDelete = 0 and iDepId = :iDepId:',
                    'bind'       => ['iDepId' => $inDepId]
                ]);
                if (!$outDep || !$outDep->sTag || !$inDep || !$inDep->sTag) {
                    return $this->sendViewError('未找到部门标识或者部门不存在');
                }
                if ($obj->iState == 2 && !$this->hasCheckPower('dep', $outDep->sTag)) {
                    return $this->sendErrorResponse('没有权限');
                }
                if ($obj->iState == 3 && !$this->hasCheckPower('dep', $inDep->sTag)) {
                    return $this->sendErrorResponse('没有权限');
                }
                if ($obj->iState == 4 && !$this->hasCheckPower('resource', 'XHRLB')) {
                    return $this->sendErrorResponse('没有权限');
                }
                if ($obj->iState == 5 && !$this->hasCheckPower('manager')) {
                    return $this->sendErrorResponse('没有权限');
                }
            }
            switch ($obj->iState) {
                case 1:
                    $type = 'mine';
                    break;
                case 2:
                    $type = 'outDep';
                    break;
                case 3:
                    $type = 'inDep';
                    break;
                case 4:
                    $type = 'resource';
                    break;
                case 5:
                    $type = 'manager';
                    break;
                default:
                    $type = '';
            }
            if (!$type) {
                return $this->sendErrorResponse(400, '未知状态');
            }
            $this->db->begin();
            if ($pass == 1) {
                $obj->iState = $obj->iState + 1 ;
            } elseif ($pass == 2) {
                $obj->iState = 7 ;
            } else {
                return $this->sendErrorResponse(500, '未知操作类型');
            }
            if ($obj->mHistory == null) {
                $history = [
                    [
                        'date'       => date('Y-m-d H:i:s'),
                        'operatorId' => Main::getLoginUserInfo('userId'),
                        'desc'       => $desc,
                        'pass'       => $pass == 1 ? '通过': '不通过',
                        'type'       => $type
                    ]
                ];
            } else {
                $history = json_decode($obj->mHistory, true);
                $history[] = [
                    'date'       => date('Y-m-d H:i:s'),
                    'operatorId' => Main::getLoginUserInfo('userId'),
                    'desc'       => $desc,
                    'pass'       => $pass == 1 ? '通过': '不通过',
                    'type'       => $type
                ];
            }
            $obj->mHistory = json_encode($history, JSON_UNESCAPED_UNICODE);
            if (!$obj->save()) {
                throw new XhException('保存失败');
            }
            if ($obj->iState == 6) { //全部确认
                $staff->sDepIds = $obj->sInDepId;
                $staff->sRegularSalary = $obj->sInSalary;
                $staff->sPostName = $obj->sInPost;
                if (!$staff->save()) {
                    throw new XhException('转正申请保存失败');
                }
            }
            $approve = new XhhrmApprove();
            $approve->sType = 'transfer';
            $approve->sVerifier = $type;
            $approve->mDesc = $desc;
            $approve->iUserId = Main::getLoginUserInfo('userId');
            $approve->iTargetId = $obj->iSTId;
            $approve->sDate     = date('Y-m-d');
            $approve->bPass     = $pass;
            if (!$approve->save()) {
                throw new XhException('保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 离职申请
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181031
     */
    public function addDismissAction()
    {
        try {
            $staffId = $this->request->getPost('staffId', 'int');
            $desc    = $this->request->getPost('desc', 'string');
            if (!$staffId) {
                return $this->sendErrorResponse(500, '缺少职工id');
            }
            $check = XhhrmStaffDismiss::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId: and iState != 4 and iState != 5  ',
                'bind'       => ['iStaffId' => $staffId],
            ]);
            if ($check) {
                return $this->sendErrorResponse(400, '离职申请已经存在请勿重复创建');
            }
            $obj = new XhhrmStaffDismiss();
            $obj->iStaffId = $staffId;
            $obj->mDesc =$desc;
            if (!$obj->save()) {
                return $this->sendErrorResponse(500, '申请保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 离职列表
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181101
     */
    public function dismissListAction()
    {
        try {
            Assets::easyUI();
            Assets::importJs('js/mine/dismissList.js');
            $this->view->setTemplateBefore('listForm');
            $this->view->pick('mine/dismissList');
            Template::exists('Mine_Dismiss', 'list') or die(Main::showMessageModal('配置文件不存在，请先创建！', 109106002));
            $listButtonArr = $formButtonArr = $listSearchArr = array();
            $state = array_map(function ($val) {
                return strip_tags($val);
            }, self::$dismissEnum['iState']);
            $listSearchArr[] = ['type'=>'select', 'id'=>'select_state', 'data'=>['' => '全部'] + $state,
                'default' => '' ,'style' => 'width: 102px;'];
            $listSearchArr[] = array('type' => 'text', 'id' => 'list_search', 'label' => ' 搜索： ');
            $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找',
                'icon' => 'fa-search', 'style' => 'margin-left:10px');

            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_check', 'text' => '审批', 'icon' => 'fa-check');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash');
            $listButtonArr[] = array('plain' => 'true', 'id' => 'bt_list_seeCheck', 'text' => '查看历史',
                'icon' => 'fa-eye');
            return $this->view->setVars([
                'List' => Template::createList('list', 'Mine_Dismiss', [
                    'searchToolbar' => Template::createSearchToolBar($listSearchArr, true),
                    'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                ]),
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 获取离职信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181101
     */
    public function getDismissAction()
    {
        try {
            $staffId = $this->request->getPost('staffId', 'int');
            $state   = $this->request->getPost('state', 'string');
            $key     = $this->request->getPost('key', 'string');
            $dismissColumns =  array_keys(get_object_vars(new XhhrmStaffDismiss()));
            $dismissColumns = array_map(function ($val) {
                return 'd.' . $val;
            }, $dismissColumns);
            $builder = $this->modelsManager->createBuilder()
                ->from(['d' => 'Admin\Models\hrm\XhhrmStaffDismiss'])
                ->columns(array_merge($dismissColumns, ['s.sStaffName', 's.sDepIds', 's.tBirthday', 's.iUserSex',
                    's.sPostName', 's.tHireDate', 's.sCultureLevel', 's.sProfession']))
                ->leftJoin('Admin\Models\hrm\XhhrmStaff', 'd.iStaffId = s.iStaffId', 's')
                ->where('d.bDelete = 0');
            if ($staffId) {
                $builder->andWhere('d.iStaffId = :iStaffId:', ['iStaffId' => $staffId]);
            }
            if ($state) {
                $builder->andWhere('d.iState = :iState:', ['iState' => $state]);
            }
            if ($key) {
                $builder->andWhere('s.sStaffName like :key:', ['key' => '%'.$key.'%']);
            }
            $data = Main::runBuilderPage($builder, self::$dismissEnum);
            foreach ($data['rows'] as $index => &$row) {
                if ($row['sDepIds']) {
                    $row['sDepName'] = XhhrmDepart::getDepName($row['sDepIds']);
                }
                $row['mDesc'] = "<div  title='{$row['mDesc']}' style='text-overflow: ellipsis;overflow: hidden;'>
                                {$row['mDesc']}</div>";
            }
            Main::runUserNameById(
                $data['rows'],
                ['iCreateUserId' => 'iCreateUserId', 'iLastModifyUserId' => 'iLastModifyUserId'],
                true
            );
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 离职审批表单
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface|\Phalcon\Mvc\View|string
     *
     * create by dale  20181102
     */
    public function dismissCheckAction()
    {
        try {
            $id = $this->request->getQuery('id', 'string');
            if (!$id) {
                return $this->sendViewError('缺少参数');
            }
            $this->view->pick('mine/dismissCheck');
            Assets::importJs('js/mine/dismissCheck.js');
            $info = XhhrmStaffDismiss::findFirst($id);
            if (!$info) {
                return $this->sendViewError('未找到对应记录');
            }
            if (!User::isAdmin()) {
                $staff = XhhrmStaff::findFirst([
                    'columns'    => 'iStaffId,sDepIds,iUserId',
                    'conditions' => 'bDelete = 0 and iStaffId = :iStaffId:',
                    'bind'       => ['iStaffId' => $info->iStaffId],
                ]);
                if (!$staff) {
                    return $this->sendViewError('未找到职工信息');
                }
                $depId = array_values(array_filter(explode(',', $staff->sDepIds)));
                $depId = end($depId);
                if (!$depId) {
                    return $this->sendViewError('未找到职工的部门信息');
                }
                $dep = XhhrmDepart::findFirst([
                    'columns'    => 'sTag',
                    'conditions' => 'bDelete = 0 and iDepId = :iDepId:',
                    'bind'       => ['iDepId' => $depId]
                ]);
                if (!$dep || !$dep->sTag) {
                    return $this->sendViewError('未找到部门标识或者部门不存在');
                }
                if ($info->iState == 1 && !$this->hasCheckPower('dep', $dep->sTag)) {
                    return $this->sendViewError('没有权限');
                }
                if ($info->iState == 2 && !$this->hasCheckPower('resource', 'XHRLB')) {
                    return $this->sendViewError('没有权限');
                }
                if ($info->iState == 3 && !$this->hasCheckPower('manager')) {
                    return $this->sendViewError('没有权限');
                }
            }
            return $this->view->setVars([
                'info' => $info->toArray()
            ]);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 离职面谈记录
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181102
     */
    public function changeDismissStatusAction()
    {
        try {
            $id   = $this->request->getPost('id', 'int');
            $pass = $this->request->getPost('pass', 'int');//1 通过 2 不通过
            $desc = $this->request->getPost('desc', 'string');
            if (!$id || !$pass || !$desc) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $obj = XhhrmStaffDismiss::findFirst($id);
            if (!$obj) {
                return $this->sendErrorResponse(400, '未找到对应的记录');
            }
            if ($obj->iState == 4) {
                return $this->sendErrorResponse(500, '已经审批通过');
            }
            if ($obj->iState == 5) {
                return $this->sendErrorResponse(500, '已经审批不通过');
            }
            $staff = XhhrmStaff::findFirst([
                'conditions' => 'bDelete = 0 and iStaffId = :iStaffId:',
                'bind'       => ['iStaffId' => $obj->iStaffId],
            ]);
            if (!$staff) {
                return $this->sendErrorResponse(400, '未找到职工信息');
            }
            if ($staff->iStaffStatus && $staff->iStaffStatus == 2) {
                return $this->sendErrorResponse(500, '该职工已经离职');
            }
            if (!User::isAdmin()) { //判断权限
                $depId = array_values(array_filter(explode(',', $staff->sDepIds)));
                $depId = end($depId);
                if (!$depId) {
                    return $this->sendErrorResponse(400, '未找到职工的部门信息');
                }
                $dep = XhhrmDepart::findFirst([
                    'conditions' => 'bDelete = 0 and iDepId = :iDepId:',
                    'bind'       => ['iDepId' => $depId]
                ]);
                if (!$dep || !$dep->sTag) {
                    return $this->sendErrorResponse(400, '未找到部门标识或者部门不存在');
                }
                if ($obj->iState == 1 && !$this->hasCheckPower('dep', $dep->sTag)) {
                    return $this->sendErrorResponse(403, '没有权限');
                }
                if ($obj->iState == 2 && !$this->hasCheckPower('resource', 'XHRLB')) {
                    return $this->sendErrorResponse(403, '没有权限');
                }
                if ($obj->iState == 3 && !$this->hasCheckPower('manager')) {
                    return $this->sendErrorResponse(403, '没有权限');
                }
            }
            switch ($obj->iState) {
                case 1:
                    $type = 'dep';
                    break;
                case 2:
                    $type = 'resource';
                    break;
                case 3:
                    $type = 'manager';
                    break;
                default:
                    $type = '';
            }
            if (!$type) {
                return $this->sendErrorResponse(400, '未知状态');
            }
            $this->db->begin();
            if ($pass == 1) {
                $obj->iState = $obj->iState + 1 ;
            } elseif ($pass == 2) {
                $obj->iState = 5 ;
            } else {
                return $this->sendErrorResponse(500, '未知操作类型');
            }
            if ($obj->mHistory == null) {
                $history = [
                    [
                        'date'       => date('Y-m-d H:i:s'),
                        'operatorId' => Main::getLoginUserInfo('userId'),
                        'desc'       => $desc,
                        'pass'       => $pass == 1 ? '通过': '不通过',
                        'type'       => $type
                    ]
                ];
            } else {
                $history = json_decode($obj->mHistory, true);
                $history[] = [
                    'date'       => date('Y-m-d H:i:s'),
                    'operatorId' => Main::getLoginUserInfo('userId'),
                    'desc'       => $desc,
                    'pass'       => $pass == 1 ? '通过': '不通过',
                    'type'       => $type
                ];
            }
            $obj->mHistory = json_encode($history, JSON_UNESCAPED_UNICODE);
            if (!$obj->save()) {
                throw new XhException('保存失败');
            }
            if ($obj->iState == 4 ) {
                //todo 离职交接工作
                $staff->iStaffStatus = 2;
                $staff->tLeaveTime  = date('Y-m-d');
                if ($staff->mHistory == null) {
                    $staff->mHistory = json_encode([
                        [
                            'time' =>  date('Y-m-d'),
                            'type' => 'iStaffStatus',
                            'status' => 2,
                            'operator' => Main::getLoginUserInfo('userId'),
                            'operateTime' => date("Y-m-d H:i:s", time())
                        ]
                    ]);
                } else {
                    $arr = json_decode($staff->mHistory, true);
                    $arr[] = [
                        'time' =>  date('Y-m-d'),
                        'type' => 'iStaffStatus',
                        'status' => 2,
                        'operator' => Main::getLoginUserInfo('userId'),
                        'operateTime' => date("Y-m-d H:i:s", time())
                    ];
                    $staff->mHistory = json_encode($arr);
                }
                if (!$staff->save()) {
                    throw new XhException('离职录入失败');
                }
            }
            $approve = new XhhrmApprove();
            $approve->sType = 'dismiss';
            $approve->sVerifier = $type;
            $approve->mDesc = $desc;
            $approve->iUserId = Main::getLoginUserInfo('userId');
            $approve->iTargetId = $obj->iSDId;
            $approve->sDate     = date('Y-m-d');
            $approve->bPass     = $pass;
            if (!$approve->save()) {
                throw new XhException('保存失败');
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }




    /**
     * 获取出生年月
     *
     * @param $birthday
     *
     * @return false|string
     *
     * create by dale  20181026
     */
    public function getAge($birthday = '')
    {
        if (!$birthday) {
            return 0;
        }
        list($year, $month, $day) = explode("-", $birthday);
        $year_diff = date("Y") - $year;
        $month_diff = date("m") - $month;
        $day_diff = date("d") - $day;
        if ($day_diff < 0 || $month_diff < 0) {
            $year_diff--;
        }
        return $year_diff;
    }

    /**
     * 职工领用信息
     *
     * @return \Phalcon\Mvc\View|string
     *
     * create by dale  20181220
     */
    public function staffReceiveAction()
    {
        try {
            $this->view->pick('mine/staffReceive');
            Assets::importJs('js/mine/staffReceive.js');
            $staffId = $this->getLoginStaffId();
            $staff = XhhrmStaff::findFirst($staffId);
            if (!$staff) {
                return $this->sendViewError('未找到职工记录');
            }
            if (!$staff->iUserId) {
                return $this->sendViewError('未与职工账号关联');
            }
            //out
            $lmData = Lm::getOutGoodsDataByUserId($staff->iUserId);
            //in
            $lmInData = Lm::getInGoodsDataByUserId($staff->iUserId);
//            var_dump($lmInData);die;
            $selfTabletData =  Device::getRegisterDataByUserId($staff->iUserId, 1); //自用机
            $backTabletData =  Device::getRegisterDataByUserId($staff->iUserId, 2); //备用机
            Main::runSchoolNameByIdStr($selfTabletData, ['iSchoolId' => 'sSchoolName'], true);
            Main::runSchoolNameByIdStr($backTabletData, ['iSchoolId' => 'sSchoolName'], true);

            return $this->view->setVars([
                'lmData' => $lmData,
                'lmInData' => $lmInData,
                'selfTabletData' => $selfTabletData,
                'backTabletData' => $backTabletData
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 职工账号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181220
     */
    public function staffAccountAction()
    {
        try {
            $this->view->pick('mine/staffAccount');
            Assets::importJs('js/mine/staffAccount.js');
            $staffId = $this->getLoginStaffId();
            $staff = XhhrmStaff::findFirst($staffId);
            if (!$staff) {
                return $this->sendViewError('未找到职工记录');
            }
            if (!$staff->iUserId) {
                return $this->sendViewError('未与职工账号关联');
            }

        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 职工账号
     *
     * @return string
     *
     * create by dale  20181225
     */
    public function staffFunctionAction()
    {
        try {
            $this->view->pick('mine/staffFunction');
            Assets::easyUI();
            Assets::importCss('css/icons.css');
            Assets::importJs('js/mine/staffFunction.js');
            $staffId = $this->getLoginStaffId();
            $staff = XhhrmStaff::findFirst($staffId);
            if (!$staff) {
                return $this->sendViewError('未找到职工记录');
            }
            $staffManage = $this->getStaffManage($staff->toArray());
//            var_dump($staffManage);die;
            return $this->view->setVars([
                'staffManage' => $staffManage
            ]);
        } catch (\Exception $e) {
            return $this->sendViewError(
                $e->getMessage()
            );
        }
    }

    /**
     * 获取职工邮箱
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181225
     */
    public function getStaffHundredMailAction()
    {
        try {
            $staffId = $this->getLoginStaffId();
            $staff = XhhrmStaff::findFirst($staffId);
            if (!$staff) {
                return $this->sendErrorResponse(400, '未找到职工记录');
            }
            if(!$staff->sHundredMail) {
                return $this->sendErrorResponse(500, '未找到职工百分邮箱');
            }
            return $this->sendJsonResponse(['email' => $staff->sHundredMail], true);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 改变邮箱密码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181225
     */
    public function changeMailPasswordAction()
    {
        try {
            $email = $this->request->getPost('email', 'string');
            $password = $this->request->getPost('password', 'string');
            if (!$email || !$password) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $staffId = $this->getLoginStaffId();
            $staff = XhhrmStaff::findFirst($staffId);
            if (!$staff) {
                return $this->sendErrorResponse(400, '未找到职工记录');
            }
            if ($staff->sHundredMail != $email) {
                return $this->sendErrorResponse(500, '职工的邮箱与需修改的邮箱不一致');
            }
            if (!HundredMail::checkMail($email)) {
                return $this->sendErrorResponse(500, '邮箱未创建');
            }
            $res = HundredMail::modifyMailPassword($email, $password);
            if (!$res) {
                return $this->sendErrorResponse(500, '修改邮箱密码失败');
            }
            return $this->sendSuccessResponse('修改邮箱密码成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }

    /**
     * 创建邮箱
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181225
     */
    public function createMailAction()
    {
        try {
            $password = $this->request->getPost('password', 'string');
            if (!$password) {
                return $this->sendErrorResponse(400, '缺少参数');
            }
            $staffId = $this->getLoginStaffId();
            $staff = XhhrmStaff::findFirst($staffId);
            if (!$staff) {
                return $this->sendErrorResponse(400, '未找到职工记录');
            }
            if (!$staff->sSelfPhone) {
                return $this->sendErrorResponse(500, '职工未设置电话');
            }
            $res = HundredMail::addMailByPhone($staff->sSelfPhone, $staff->sStaffName, $password);
            if (!$res) {
                return $this->sendErrorResponse(500, '新增邮箱失败');
            }
            $staff->sHundredMail = $staff->sSelfPhone . '@100fen.cn';
            if (!$staff->save()) {
                return $this->sendErrorResponse(500, '职工百分邮箱保存失败');
            }
            return $this->sendSuccessResponse('新增邮箱成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(
                500,
                $e->getMessage(),
                $e instanceof XhException ? $e->getDescription() : $e->getTrace()
            );
        }
    }


    /**
     * 获取职工功能模块
     *
     * @param $staff
     *
     * @return array
     *
     * create by dale  20181225
     */
    public function getStaffManage($staff)
    {
        $arr = [];
        $hundredEmail = Tool::getValue($staff, 'sHundredMail');
        if (!$hundredEmail) {
            $arr[] = [
                'iconClass' => 'icon-email',
                'id' => 'addMail',
                'title' => '添加百分邮箱',
            ];
        } else {
            $arr[] = [
                'iconClass' => 'icon-email',
                'id' => 'modifyMailPassword',
                'title' => '修改百分邮箱密码',
            ];
        }

//        for ($i= 0 ; $i <= 9; $i++) {
//            $arr[] = $arr[0];
//        }
        return $arr;
    }



}